package vn.orderonline.core.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import vn.orderonline.core.dao.common.GenericDaoImpl;
import vn.orderonline.core.dao.entity.MenuFood;

@Repository
public class MenuFoodDaoImpl extends GenericDaoImpl<MenuFood, Integer>
		implements MenuFoodDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<Object[]> getListMenuFoodByRestaurantId(Integer resId) {
		String hql = "Select rmf.id.restaurantId, re.restaurantName, rmf.id.menuFoodId, mf.menuFoodName "
				+ "From Restaurant re, RestaurantMenuFood rmf, MenuFood mf "
				+ "Where re.restaurantId = rmf.id.restaurantId and rmf.id.menuFoodId = mf.menuFoodId and rmf.id.restaurantId = :restaurantId";
		Query query = getSession().createQuery(hql.toString());
		query.setParameter("restaurantId", resId);
		return query.list();
	}

	@Override
	public Boolean checkExistedMenuName(Integer resId, String menuName) {
		String hql = "From RestaurantMenuFood rmf, MenuFood mf "
				+ "Where rmf.id.menuFoodId = mf.menuFoodId And rmf.id.restaurantId = :restaurantId And mf.menuFoodName = :menuFoodName";
		Query query = getSession().createQuery(hql.toString());
		query.setParameter("restaurantId", resId);
		query.setParameter("menuFoodName", menuName);
		return !query.list().isEmpty() ? true : false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, String> getAllMenuFoodIdAndNameByResId(Integer resId) {
		Criteria criteria = getSession().createCriteria(MenuFood.class);
		criteria.setProjection(Projections.projectionList()
				.add(Projections.property("menuFoodId"))
				.add(Projections.property("menuFoodName")));
		List<Object[]> list = criteria.list();
		Map<String, String> map = new HashMap<String, String>();
		for (Object[] obj : list) {
			map.put(obj[0].toString(), obj[1].toString());
		}
		return map;
	}

	@Override
	public String getMenuFoodNameByMenuFoodId(Integer menuFoodId) {
		Criteria criteria = getSession().createCriteria(MenuFood.class);
		criteria.setProjection(Projections.property("menuFoodName"));
		criteria.add(Restrictions.eq("menuFoodId", menuFoodId));
		return (String) criteria.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<String> getMenuFoodNameByResId(Integer resId) {
		String hql = "Select mf.menuFoodName "
				+ "From Restaurant r, RestaurantMenuFood rm, MenuFood mf "
				+ "Where r.restaurantId = rm.id.restaurantId and rm.id.menuFoodId = mf.menuFoodId and "
				+ "r.restaurantId = :restaurantId";
		Query query = getSession().createQuery(hql);
		query.setParameter("restaurantId", resId);
		return query.list();
	}

}
